package com.anmai.crawler1.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anmai.crawler1.dao.BaiduInfoDao;
import com.anmai.crawler1.dao.CityDao;
import com.anmai.crawler1.dao.ShopDao;
import com.anmai.crawler1.dao.TagDao;
import com.anmai.crawler1.entity.CityBean;
import com.anmai.crawler1.entity.TagBean;
import com.anmai.crawler1.utils.JsoupUtils;
import org.jsoup.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("baiduService")
public class BaiduService {

    private final Logger logger = LoggerFactory.getLogger(BaiduService.class);

    @Autowired
    private ShopDao shopDao;

    @Autowired
    private CityDao cityDao;

    @Autowired
    private BaiduInfoDao baiduInfoDao;

    @Autowired
    private TagDao tagDao;

    //获取周边信息
    public void getNearInfo(){

        //获取城市列表
        List<CityBean> regions = cityDao.selectCities();
        //获取tags信息
        List<TagBean> tagBeans =   tagDao.selectTagsExceptStatus(0);
        Map<String, String> map = new HashMap<>();
        regions.stream().forEach(cityBean -> {
            map.put("page_num", "0");
            map.put("region",cityBean.getCityName().trim());
            tagBeans.stream().forEach(tagBean -> {
                map.put("query", tagBean.getSecond().trim());
                try {
                    String infoJson = BaiduService.getInfoJson(map);
                    JSONObject json = JSON.parseObject(infoJson);

                    tagBean.setStatus(-1);
                    tagBean.setUpdateTime(new Date());
                    tagDao.updateByPrimaryKeySelective(tagBean);
                } catch (IOException e) {
                    //修改tags的状态
                    tagBean.setStatus(-1);
                    tagBean.setUpdateTime(new Date());
                    tagDao.updateByPrimaryKeySelective(tagBean);
                    logger.error("ERROR:getNearInfo---->"+tagBean.getFirst()+"====="+tagBean.getSecond());
                    e.printStackTrace();
                }
            });
        });


    }

    //将存取baidu_info中的信息
    public static  void  saveBaiduInfoJson(String json,BaiduInfoDao baiduInfoDao){

    }


    //获取百度的json文件
    public static String getInfoJson(Map<String,String> map) throws IOException {
        Connection conn = JsoupUtils.getConnection("http://api.map.baidu.com/place/v2/search?output=json&page_size=20&=5&scope=2");
        conn.data("query", map.get("query"));
        conn.data("region", map.get("region"));
        conn.data("ak", "R6gk5NM0fXNpjouptg647WtYnU4F949X");
        conn.data("page_num", map.get("page_number"));
        return conn.ignoreContentType(true).execute().body();
    }

}
